package cn.shuangze.assetsms.view;

import cn.shuangze.assetsms.component.MyJTable;
import cn.shuangze.assetsms.dao.AssetsTypeDao;
import cn.shuangze.assetsms.dao.impl.AssetsTypeDaoJDBCImpl;
import cn.shuangze.assetsms.entity.AssetsType;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.event.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;


/**
 * 资产类别信息综合管理类
 *
 * @author HanXiaohu
 */
public class AssetsTypeManagement extends JDialog implements ActionListener, ListSelectionListener {

    private AssetsTypeDao assetsTypeDao;
    private Thread showThread;

    //定义所用的面板
    private JPanel northPanel = new JPanel();
    private JPanel centerPanel = new JPanel();
    private JPanel southPanel = new JPanel();

    //框架的大小
    private Dimension viewSize = new Dimension(400, 300);
    private Font font = new Font("Dialog", Font.PLAIN, 12);

    //定义图形界面元素
    private JLabel jLabel1 = new JLabel();
    private JLabel jLabel2 = new JLabel();
    private JLabel jLabel3 = new JLabel();

    private JTextField jTextField1 = new JTextField(15);
    private JTextField jTextField2 = new JTextField(15);
    private JTextField jTextField3 = new JTextField(15);

    private JButton addInfo = new JButton(new ImageIcon("images\\save.png"));
    private JButton modifyInfo = new JButton(new ImageIcon("images\\save.png"));
    private JButton deleteInfo = new JButton(new ImageIcon("images\\delete.png"));
    private JButton clearInfo = new JButton(new ImageIcon("images\\delete.png"));
    private JButton exitInfo = new JButton(new ImageIcon("images\\down.png"));

    //定义表格
    private JScrollPane jScrollPane1;
    private JTable jTable;
    private DefaultTableModel tableModel;
    private ListSelectionModel listSelectionModel = null;


    public AssetsTypeManagement() {

        assetsTypeDao = new AssetsTypeDaoJDBCImpl();

        showThread = new Thread(() -> {
            try {
                showTableData();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "窗口初始化错误，错误原因：" + e.getMessage(),
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        //界面初始化
        init();

    }

    private void init() {
        Container contentPane = this.getContentPane();
        contentPane.setLayout(new BorderLayout());

        this.setModal(true);  //模式对话框
        this.setSize(viewSize);

        //设置标题
        this.setTitle("资产类别管理");
        this.setResizable(false);

        //设置运行时窗口的位置
        this.setLocationRelativeTo(null);

        //北部面板的布局
        tableModel = new DefaultTableModel();  // 创建默认表格模式
        jTable = new MyJTable(tableModel);  // 创建表格 禁用编辑功能
        listSelectionModel = jTable.getSelectionModel();
        listSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  // 设置表格选择模式为单一选择
        jScrollPane1 = new JScrollPane(jTable);  // 创建一个滚动面板，包含表格
        jScrollPane1.setPreferredSize(viewSize);  //设置滚动面板大小
        DefaultTableCellRenderer cr = new DefaultTableCellRenderer();
        cr.setHorizontalAlignment(JLabel.CENTER);  //表格内容居中
        jTable.setDefaultRenderer(Object.class, cr);
        //jTable.getTableHeader().setReorderingAllowed(false);  //禁止表头列拖动

        showThread.start();

        northPanel.add(jScrollPane1);  // 将滚动面板添加到Panel


        //中部面板的布局
        jLabel1.setText("编号");
        jLabel1.setFont(font);
        centerPanel.add(jLabel1);
        centerPanel.add(jTextField1);

        jLabel2.setText("大类");
        jLabel2.setFont(font);
        centerPanel.add(jLabel2);
        centerPanel.add(jTextField2);

        jLabel3.setText("小类");
        jLabel3.setFont(font);
        centerPanel.add(jLabel3);
        centerPanel.add(jTextField3);


        //南部面板的布局
        addInfo.setText("增加");
        addInfo.setFont(font);
        southPanel.add(addInfo);

        modifyInfo.setText("修改");
        modifyInfo.setFont(font);
        southPanel.add(modifyInfo);

        deleteInfo.setText("删除");
        deleteInfo.setFont(font);
        southPanel.add(deleteInfo);

        clearInfo.setText("清空");
        clearInfo.setFont(font);
        southPanel.add(clearInfo);

        exitInfo.setText("退出");
        exitInfo.setFont(font);
        southPanel.add(exitInfo);


        //添加Panel到contentPane
        contentPane.add(northPanel, BorderLayout.NORTH);
        contentPane.add(centerPanel, BorderLayout.CENTER);
        contentPane.add(southPanel, BorderLayout.SOUTH);

        //添加事件侦听
        addInfo.addActionListener(this);
        modifyInfo.addActionListener(this);
        deleteInfo.addActionListener(this);
        clearInfo.addActionListener(this);
        exitInfo.addActionListener(this);
        listSelectionModel.addListSelectionListener(this);
        jScrollPane1.addMouseListener(new TableMouseEvent());


        //设置状态
        setDefaultStatus();
        jTextField1.setEditable(false);

    }

    /**
     * 按钮事件处理
     *
     * @param e
     */
    public void actionPerformed(ActionEvent e) {
        Object obj = e.getSource();
        if (obj == clearInfo) {   //清空
            setDefaultStatus();

        } else if (obj == exitInfo) {   //退出
            this.dispose();

        } else {

            try {

                if (obj == addInfo) {

                    assetsTypeDao.add(new AssetsType(jTextField2.getText(), jTextField3.getText()));
                    JOptionPane.showMessageDialog(this, "资产类别添加成功！",
                            "资产类别添加", JOptionPane.INFORMATION_MESSAGE);

                } else if (obj == modifyInfo) {

                    assetsTypeDao.modify(new AssetsType(Integer.parseInt(jTextField1.getText()), jTextField2.getText(), jTextField3.getText()));
                    JOptionPane.showMessageDialog(this, "资产类别修改成功！",
                            "资产类别修改", JOptionPane.INFORMATION_MESSAGE);

                } else if (obj == deleteInfo) {

                    int i = 1;
                    if (!jTextField1.getText().equals("")) {
                        i = JOptionPane.showConfirmDialog(this, "确定要删除吗?",
                                null, JOptionPane.YES_NO_OPTION);//单击"确定"按钮,则返回值为0.
                    }
                    if (i == 0) {
                        assetsTypeDao.delete(Integer.parseInt(jTextField1.getText()));
                        JOptionPane.showMessageDialog(this, "资产类别删除成功！",
                                "资产类别删除", JOptionPane.INFORMATION_MESSAGE);
                    }
                }

                setDefaultStatus();
                showTableData();

            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "数据库访问错误，错误原因：" + ex.getMessage(),
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    /**
     * 恢复默认状态
     */
    void setDefaultStatus() {
        jTextField1.setText(null);
        jTextField2.setText(null);
        jTextField3.setText(null);

        addInfo.setEnabled(true);
        modifyInfo.setEnabled(false);
        deleteInfo.setEnabled(false);

        jTable.getSelectionModel().clearSelection(); //取消表格选中
    }

    /**
     * 显示Table数据
     */
    private void showTableData() throws Exception {

        String[][] colValue = assetsTypeDao.findAll();
        if (colValue == null) {
            colValue = new String[1][3];
        }

        String[] colName = {"资产类别编号", "资产大类", "资产小类"};
        tableModel.setDataVector(colValue, colName);
        jTable.revalidate();  //刷新表格
    }

    /**
     * 当表格被选中时的操作
     *
     * @param lse
     */
    public void valueChanged(ListSelectionEvent lse) {
        int selectedRow = jTable.getSelectedRow();
        if (selectedRow != -1) {
            jTextField1.setText((String) tableModel.getValueAt(selectedRow, 0));
            jTextField2.setText((String) tableModel.getValueAt(selectedRow, 1));
            jTextField3.setText((String) tableModel.getValueAt(selectedRow, 2));

            //设置是否可操作
            addInfo.setEnabled(false);
            modifyInfo.setEnabled(true);
            deleteInfo.setEnabled(true);
        } else {
            setDefaultStatus();
        }
    }


    class TableMouseEvent implements MouseListener {

        @Override
        public void mouseClicked(MouseEvent e) {
            setDefaultStatus();  //点击滚动面板空白处恢复默认状态
        }

        @Override
        public void mousePressed(MouseEvent e) {

        }

        @Override
        public void mouseReleased(MouseEvent e) {

        }

        @Override
        public void mouseEntered(MouseEvent e) {

        }

        @Override
        public void mouseExited(MouseEvent e) {

        }
    }

}
